#include <iostream>
using std::cout;
using std::endl;

void test0(){
    int * p = (int*)malloc(sizeof(int));
    *p = 100;
    free(p);

    //<>里面是转换的目标类型
    //()里面是待转换的内容
    int * p2 = static_cast<int*>(malloc(sizeof(int)));
    *p2 = 100;
    free(p2);

    const char * pstr = "hello";
    /* pstr[0] = 'H'; */
    /* cout << pstr[0] << endl; */

    int * pint = (int*)pstr;
    /* int * pint2 = static_cast<int*>(pstr); */

    char * pc = (char*)pstr;
    /* pc[0] = 'X'; */
    //直接不允许进行这些不合理的转换
    /* char * pc2 = static_cast<char*>(pstr); */
}

void test1(){
    //当指向常量的指针确实指向的是常量时
    //进行const_cast转换成普通指针后
    //如果利用指针进行写操作
    //不会改变const常量本体的值
    const int num = 100;
    /* const_cast<int>(num); */
    const int * pn = &num;
    int * pn2 = const_cast<int*>(pn);
    *pn2 = 400;
    cout << num << endl;
    cout << *pn2 << endl;
    cout << &num << endl;
    cout << pn2 << endl;





    cout << endl;
    //const_cast去除const属性，但是只能对引用或指针使用
    int num2 = 10;
    const int & ref = num2;
    /* ref = 90; */
    int & rr = const_cast<int&>(ref);
    rr = 90;
    cout << num2 << endl;

    //当指向常量的指针指向的是普通的变量时
    //进行const_cast转换成普通指针后
    //如果利用指针进行写操作
    //会改变const常量本体的值
    const int * p = &num2;
    /* *p = 80; */
    int * p2 = const_cast<int*>(p);
    *p2 = 80;
    cout << num2 << endl;

}


int main(void){
    test1();
    return 0;
}
